package com.foreveross.chameleon.user.plugin;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.foreveross.bsl.test.R;
import com.foreveross.chameleon.ModuleManager;
import com.foreveross.chameleon.config.ChameleonConfig;
import com.foreveross.chameleon.config.ChameleonConstants;
import com.foreveross.chameleon.listener.AppCheckUpdateListener;
import com.foreveross.chameleon.listener.AsyncTaskListener;
import com.foreveross.chameleon.manager.BroadcastManager;
import com.foreveross.chameleon.model.ApplicationInfo;
import com.foreveross.chameleon.model.ModuleInfo;
import com.foreveross.chameleon.task.AppSyncCheckUpdateTask;
import com.foreveross.chameleon.task.ModuleSyncUpdateTask;
import com.google.gson.Gson;

/**
 * @description 模块操作插件
 * @author zhouzhineng
 *
 */
public class ModuleOperationPlugin extends CordovaPlugin{

	private final String TAG = "ModuleOperationPlugin";
	private String retJsonData = null,identify = null;
	private CallbackContext mCbCtx;
	@Override
	public boolean execute(final String action, JSONArray args,
			final CallbackContext callbackContext) throws JSONException {
		// TODO Auto-generated method stub
		mCbCtx = callbackContext;
		ModuleInfo module = null;
		List<ModuleInfo> opModules = new ArrayList<ModuleInfo>();
		ApplicationInfo app = ApplicationInfo.getInstance(cordova.getActivity());
		if(action.equals("getInstalledModuleList")) {				//获取安装的模块列表
			retJsonData = new Gson().toJson(app.getModules());
			String mainModuleTag = app.getMainModuleTag();
			retJsonData = "{\"mainModuleTag\":\"" + mainModuleTag + "\",\"list\":" + retJsonData + "}";
			PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, retJsonData);
            pluginResult.setKeepCallback(true);
            mCbCtx.sendPluginResult(pluginResult);
		} else if(action.equals("deleteModule")) {					//删除模块
			identify = args.getString(0);
			module = getModuleFromSet(app.getModules(),identify);
			if(module != null) {
				opModules.add(module);
				ModuleManager.getInstance(cordova.getActivity()).uninstall(opModules);
				retJsonData = "{}";
			} else {
				BroadcastManager.getInstance().sendModuleUninstallState(identify, false);
			}
		} else if(action.equals("checkAppUpdate")) {
			syncApp();
		} else if(action.equals("test")) {
			identify = args.getString(0);
			Intent it = new Intent(ChameleonConstants.ACTION_MODULE_DOWNLOAD_PROGRESS_UPDATE);
			it.putExtra("identify", identify);
			it.putExtra("progress", 25);
			cordova.getActivity().sendBroadcast(it);
			
		}else {
			if(action.equals("installModule") || action.equals("upgradeModule")) {
				identify = args.getString(0);
			}
			syncModules(action);
			
		} /*else if(action.equals("installModule")) {	//安装模块
			identify = args.getString(0);
			module = getModuleFromSet(app.getUninstallModules(),identify);
			opModules.add(module);
			ModuleManager.getInstance(cordova.getActivity()).autoDownload(opModules);
		} else if(action.equals("upgradeModule")) {					//升级模块
			identify = args.getString(0);
			module = getModuleFromSet(app.getUpgradeModules(),identify);
			opModules.add(module);
			ModuleManager.getInstance(cordova.getActivity()).autoUpgrade(opModules);
		} */
		return true;
	}

	protected void syncApp() {
		ApplicationInfo curInfo = ApplicationInfo.getInstance(cordova.getActivity());
		AppSyncCheckUpdateTask appUpdateTask = new AppSyncCheckUpdateTask(
				curInfo, new AppCheckUpdateListener(cordova.getActivity()));
		appUpdateTask.execute();
	}
	/**
	 * 同步模块
	 */
	private void syncModules(final String action) {
		final Activity activity = cordova.getActivity();
		ModuleSyncUpdateTask moduleSyncTask = new ModuleSyncUpdateTask(activity,
				new AsyncTaskListener() {

					@Override
					public void onSucc(String result) {
						// TODO Auto-generated method stub
						ApplicationInfo remoteInfo = ApplicationInfo
								.buildApplication(result);
						ChameleonConfig.REMOTE_MAIN_MODULE_TAG = remoteInfo.getMainModuleTag();
						ApplicationInfo localInfo = ApplicationInfo.getInstance(activity);
						localInfo.compareAndSetAppInfo(remoteInfo);
						boolean appendMainModuleTag = false;
						if(action.equals("getUninstallModuleList")) {
							retJsonData = new Gson().toJson(localInfo.getUninstallModules());
							appendMainModuleTag = true;
						} else if(action.equals("getUpgradeableModuleList")) {
							retJsonData = new Gson().toJson(localInfo.getUpgradeModules());
							appendMainModuleTag = true;
						} else if(action.equals("getAllModuleList")) {
							retJsonData = new Gson().toJson(resetRemoteModuleType(remoteInfo.getModules()));
							appendMainModuleTag = true;
						} else if(action.equals("installModule")) {
							ModuleInfo remoteModule = getModuleFromSet(remoteInfo.getModules(),identify);
							ModuleInfo localModule = localInfo.getModule(identify);
							if(localModule == null || localModule.getBuild() < remoteModule.getBuild()) {
								List<ModuleInfo> opModules = new ArrayList<ModuleInfo>();
								opModules.add(remoteModule);
								ModuleManager.getInstance(cordova.getActivity()).autoDownload(opModules);
							} else {
								BroadcastManager.getInstance().sendModuleInstallState(remoteModule.getIdentifier(), false);
							}
						} else if(action.equals("upgradeModule")) {
							ModuleInfo localModule = localInfo.getModule(identify);
							ModuleInfo remoteModule = getModuleFromSet(remoteInfo.getModules(),identify);
							if(localModule != null && remoteModule != null && remoteModule.getBuild() > localModule.getBuild()) {
								List<ModuleInfo> opModules = new ArrayList<ModuleInfo>();
								opModules.add(remoteModule);
								ModuleManager.getInstance(cordova.getActivity()).autoUpgrade(opModules);
							} else {
								BroadcastManager.getInstance().sendModuleUpgradeState(remoteModule.getIdentifier(), false);
							}
						}
						
						//callbackContext.success(retJsonData);
						if(appendMainModuleTag) {
							String mainModuleTag = remoteInfo.getMainModuleTag();
							retJsonData = "{\"mainModuleTag\":\"" + mainModuleTag + "\",\"list\":" + retJsonData + "}";
						}
						Log.e("ModuleOperationPlugin","resultJsonData=======>" + retJsonData);
						PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, retJsonData);
		                pluginResult.setKeepCallback(true);
		                mCbCtx.sendPluginResult(pluginResult);
					}

					@Override
					public void onFail(int errcode) {
						// TODO Auto-generated method stub
						//Toast.makeText(activity, activity.getString(R.string.module_sync_fail),
						//		Toast.LENGTH_LONG).show();
					}

				});
		moduleSyncTask.exec();
	}
	
	private ModuleInfo getModuleFromSet(Set<ModuleInfo> modules,String identify) {
		for(ModuleInfo module  : modules) {
			Log.e("ModuleOperationPlugin","模块标识:===>" + module.getIdentifier());
			if(module.getIdentifier().equals(identify)) {
				return module;
			}
		}
		return null;
	}
	
	private Set<ModuleInfo> resetRemoteModuleType(Set<ModuleInfo> remoteModules) {
		ModuleInfo module,localModule;
		ApplicationInfo appInfo = ApplicationInfo.getInstance(cordova.getActivity());
		if(remoteModules != null) {
			Iterator<ModuleInfo> it = remoteModules.iterator();
			while(it.hasNext()){
		        module = it.next();
		        File file = new File(ChameleonConfig.APP_PATH + "/www/" + module.getIdentifier());
		        if(file.exists()) {
		        	module.setModuleType(ModuleInfo.INSTALLED);
		        	localModule = appInfo.getModule(module.getIdentifier());
		        	if(localModule.getBuild() < module.getBuild()) {
		        		module.setModuleType(ModuleInfo.UPGRADABLE);
		        	}
		        }
		    }
		}
		return remoteModules;
	}
}
